import java.net.Socket; 
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

/**
   Chat-client
*/
public class Client {
    private static int connectionPort = 8989;
    private static PrintWriter out = null;
    private static BufferedReader in = null;
    
    public static void main(String[] args) throws IOException {
        
/**
	Declaration of the sockets and the objects that sends data
	between the server and the client part of the program
*/
        Socket socket = null;
        String adress = "";
		Reader reader;

/**
	Try/catch statement for handling events when no ip-adress is specified
*/
        try {
            adress = args[0];
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Missing argument ip-adress");
            System.exit(1);
        }

/**
	Try/catch statement for handling events when errors contacting the specified ip
*/

        try {
            socket = new Socket(adress, connectionPort); 
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader
                                    (socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Unknown host: " +adress);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't open connection to " + adress);
            System.exit(1);
        }

        System.out.println("Connecting to server... ");
		reader = new Reader();

		reader.start();
		System.out.println("Connected to server... ");

		String msg;
		try {
			while(true){
				if((msg = in.readLine()) == null) {
					System.exit(1);	
				}
				System.out.println(msg); //read line from server and print it
				Thread.currentThread().yield();
			}
		}catch(IOException e) {
			System.exit(1);
		}
    }
	
	/**
	A thread that reads from keyboard and sends the line to the server.
	*/
	private static class Reader extends Thread {
		public Reader(){}
		String tmp;
		public void run() {
			try {
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				while(true){
					if((tmp = in.readLine()) != null)
						out.println(tmp); //read the line, and send it to server
				}
			}catch(IOException e) {
				System.exit(1);
			}
		}
	}
}   
        
        
